package model

import (
	"log"
	"poker/db"
	"time"

	"go.mongodb.org/mongo-driver/bson"
)

// 数据上传的 channel
var dataChannel = make(chan []byte, 1000)

// 批量写入的配置
const (
	batchSize     = 100                    // 每批处理的数据量
	flushInterval = 500 * time.Millisecond // 最大等待时间
)

// 启动批量写入协程
func startBatchWriter() {
	var batch [][]byte
	// 定时器，用于在达到时间限制时触发批量写入
	timer := time.NewTimer(flushInterval)
	defer timer.Stop()

	for {
		select {
		case data := <-dataChannel:
			batch = append(batch, data)
			if len(batch) >= batchSize {
				// 达到批量大小，触发写入
				writeBatchToMongo(batch)
				batch = nil
				timer.Reset(flushInterval) // 重置定时器
			}
		case <-timer.C:
			// 达到时间限制，触发写入
			if len(batch) > 0 {
				writeBatchToMongo(batch)
				batch = nil
			}
			timer.Reset(flushInterval) // 重置定时器
		}
	}
}

// 将批量数据写入 MongoDB
func writeBatchToMongo(batch [][]byte) {
	var docs []interface{}
	for _, data := range batch {
		var doc bson.M
		err := bson.Unmarshal(data, &doc)
		if err != nil {
			log.Printf("Failed to unmarshal data: %v", err)
			continue
		}
		docs = append(docs, doc)
	}

	if len(docs) > 0 {
		err := db.InsertMany("tt", docs)
		if err != nil {
			log.Printf("Failed to insert batch into MongoDB: %v", err)
		} else {
			log.Printf("Successfully inserted %d documents", len(docs))
		}
	}
}
